﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Web.Security;

namespace TireService.Web.View.AdminView
{
    public partial class ManageMasseChange : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Bind car data to gridview
            BindCarList(db);

            // Change gridview pagesize based on dropdownlist
            gvCarList.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            BindTasks(db);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind cars to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void BindCarList(TireServiceDB db)
        {
            // Bind to gridview - show all cars that has had service
            gvCarList.DataSource = db.GetCarsByCarStatusId((int)Shared.CarStatus.TireChanged).Take(100).ToList(); ;
            gvCarList.DataBind();
        }


        /// <summary>
        /// Function that customer tasks to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void BindTasks(TireServiceDB db)
        {
            int[] tasktypestatus = new int[] { (int)Shared.TaskTypeStatus.ServiceDrive_Created, (int)Shared.TaskTypeStatus.ServiceDrive_Replan };

            var tasks = from p in db.TaskServiceDrivePlanningViews
                        join y in db.Customers on p.CustomerId equals y.CustomerId into py
                        from z in py.DefaultIfEmpty()
                        where p.TaskTypeId == (int)Shared.TaskType.ServiceDrive & p.ContainerId == 2 & tasktypestatus.Contains(p.TaskTypeStatusId) & z.CompanyName == null & p.CustomerId != 10524
                        select new
                        {
                            p.CustomerId,
                            p.PrimaryZipCode,
                            z.Email,
                        };

            gvCustomer.DataSource = tasks.ToList();
            gvCustomer.DataBind();
        }

        protected void btnMassUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                // Instantiate datalayer and business layer
                TireServiceDB db = new TireServiceDB();
                TaskBLL bll = new TaskBLL();

                // Get UserId
                Guid UserId = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                List<Car> cars = db.GetCarsByCarStatusId((int)Shared.CarStatus.TireChanged).Take(100).ToList();

                foreach (Car car in cars)
                {
                    // Get customer
                    Customer customer = db.GetCustomer(car.CustomerId);

                    // Get Tireset
                    int[] TireSetStatus = new int[] { (int)Shared.TireSetStatus.OnStock, (int)Shared.TireSetStatus.StockedAtCustomer, (int)Shared.TireSetStatus.AwaitsMoveToStock, (int)Shared.TireSetStatus.PlacedAtCustomer};
                    List<TireSet> tireset = db.GetCarTireSetByTireSetStatus(car.CarId, TireSetStatus);

                    if (tireset == null)
                    {
                        // Error
                        throw new ArgumentException("Opdatering kan ikke gennemføres - bil med reg.nr: " + car.RegistrationNumber + " har ingen hjulsæt der kan sættes på");
                    }
                    if (tireset.Count > 1)
                    {
                        // Error
                        throw new ArgumentException("Opdatering kan ikke gennemføres - bil med reg.nr: " + car.RegistrationNumber + " har 2 hjulsæt der kan sættes på");
                    }

                    int TireSetId = tireset.First().TireSetId;

                    if (customer.OnPrimaryAddressInPrimeTime)
                    {
                        // Customer Primary address selected
                        // Create servicedrive task
                        Task task = bll.CreateTask(db,
                                                    null,
                                                    (int)Shared.TaskType.ServiceDrive,
                                                    (int)Shared.TaskDetailType.ServiceDrive_ChangeTire,
                                                    (int)Shared.TaskTypeStatus.ServiceDrive_Created, customer.CustomerId, car.CarId,
                                                    TireSetId,
                                                    customer.Address,
                                                    customer.ZipCode,
                                                    customer.City,
                                                    customer.CountryId,
                                                    customer.CommentToAddress,
                                                    customer.SecondaryAddress,
                                                    customer.SecondaryZipCode,
                                                    customer.SecondaryCity,
                                                    customer.CountryId,
                                                    customer.CommentToSecondaryAddress,
                                                    null,
                                                    1,
                                                    UserId,
                                                    true);
                    }
                    else
                    {
                        // Customer Secondary address selected
                        // Create servicedrive task
                        Task task = bll.CreateTask(db,
                                                    null,
                                                    (int)Shared.TaskType.ServiceDrive,
                                                    (int)Shared.TaskDetailType.ServiceDrive_ChangeTire,
                                                    (int)Shared.TaskTypeStatus.ServiceDrive_Created, customer.CustomerId, car.CarId,
                                                    TireSetId,
                                                    customer.SecondaryAddress,
                                                    customer.SecondaryZipCode,
                                                    customer.SecondaryCity,
                                                    customer.CountryId,
                                                    customer.CommentToSecondaryAddress,
                                                    customer.Address,
                                                    customer.ZipCode,
                                                    customer.City,
                                                    customer.CountryId,
                                                    customer.CommentToAddress,
                                                    null,
                                                    1,
                                                    UserId,
                                                    true);
                    }

                    // Update car with new status
                    car.CarStatusId = (int)Shared.CarStatus.AwaitsTireChangePlanning;
                }

                db.SubmitChanges();

                BindCarList(db);

                lMessage.Text = "Opdatering gennemført";

                db.Dispose();
                
            }
            catch (Exception ex)
            {
                string error = ex.Message;

                lMessage.Text = error;
            }
        }

        protected void btnSendBookingLink_Click(object sender, EventArgs e)
        {
            try
            {
                TireServiceDB db = new TireServiceDB();

                int[] tasktypestatus = new int[] { (int)Shared.TaskTypeStatus.ServiceDrive_Created, (int)Shared.TaskTypeStatus.ServiceDrive_Replan };

                var tasks = from p in db.TaskServiceDrivePlanningViews
                            join y in db.Customers on p.CustomerId equals y.CustomerId into py
                            from z in py.DefaultIfEmpty()
                            where p.TaskTypeId == (int)Shared.TaskType.ServiceDrive & p.ContainerId == 2 & tasktypestatus.Contains(p.TaskTypeStatusId) & z.CompanyName == null & p.CustomerId != 10524
                            select new
                            {
                                p.CustomerId,
                                p.PrimaryZipCode,
                                z.Email,
                            };

                string error = "";

                foreach (var item in tasks)
                {
                    int CustomerId = Convert.ToInt32(item.CustomerId);

                    Customer customer = db.GetCustomer(CustomerId);

                    if (customer != null)
                    {
                        if (customer.UserId != null)
                        {
                            // HACK: Weblink should be a dynamic parameter
                            string BookingLink = string.Format("http://www.mobilhjulskift.dk/Booking/Booking.aspx?uid={0}", customer.UserId.ToString());

                            EmailNotificationServices emailService = new EmailNotificationServices();
                            emailService.CustomerBookingLink_SendCustomerEmail(customer.Email, customer.Name, CustomerId, Membership.GetUser(), BookingLink); 
                        }
                        else
                        {
                            // Error
                            error += "(Kunde: " + item.CustomerId.ToString() + " Fejl: Kunde har ikke et brugerlogin - venligst opret dette først)";
                        }
                    }
                    else
                    {
                        // Error
                        error += "(Kunde: " + item.CustomerId.ToString() + " Fejl: Kunde blev ikke fundet)";
                    }
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message;

                ASPxLabel1.Text = error;
            }
        }
    }
}